<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Delete, Edit, View, Search } from '@element-plus/icons-vue'
import { del, get, post, put } from '../js/http';
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const loading = ref(false)

const projectList = ref([]);

const showProjectDialog = ref(false);
const newProject = ref({});
const showRightMenu = ref(false)
const currentProject = ref({})
const showViewSettingDialog = ref(false)
const userList = ref([])
const projectUserList = ref([])
const projectUser = ref({})
const userKeyword = ref('')
const total = ref(0)
const shareProject = ref([])

const getShareProject = () => {
    get('/routing/project/shareProject').then(res => {
        shareProject.value = res.data
    })
}

const getUserData = (pageNum, pageSize) => {
    post('/auth/user/findUser', { pageNum: pageNum, pageSize: pageSize, type: userKeyword.value }).then(res => {
        userList.value = res.data.content
        total.value = res.data.totalElements
    })
}

const addUser = (userId, name, username) => {
    projectUser.value.projectId = currentProject.value.id;
    projectUser.value.userId = userId;
    projectUser.value.name = name;
    projectUser.value.username = username;
    post('/routing/project/bindUser', projectUser.value).then(res => {
        ElMessage({ type: res.status ? 'success' : 'error', message: res.message });
        getProjectUsers();
    })
}

const removeUser = (userId) => {
    get('/routing/project/clearBind', { projectId: currentProject.value.id, userId: userId }).then(res => {
        ElMessage({ type: res.status ? 'success' : 'error', message: res.message })
        getProjectUsers();
    })
}

const getProjectUsers = () => {
    get('/routing/project/users', { projectId: currentProject.value.id }).then(res => {
        projectUserList.value = res.data
    })
}

const getProjectList = (keyword, pageNum, pageSize) => {
    loading.value = true
    get('/routing/project', { keyword: keyword, pageNum: pageNum, pageSize: pageSize }).then(res => {
        if (res.status) {
            projectList.value = res.data.list;
        } else {
            ElMessage({ type: 'error', message: res.message });
        }
        loading.value = false
    })
}

const addProject = () => {
    post('/routing/project', newProject.value).then(res => {
        ElMessage({ type: res.status ? 'success' : 'error', message: res.message });
        if (res.status) {
            showProjectDialog.value = false;
            getProjectList('', 1, 20);
        }
    })
}

const goWorkspace = (project) => {
    window.open('/workspace/' + String(project.id))
}

const edit = () => {
    showProjectDialog.value = true;
    newProject.value = currentProject.value
}

const editViews = () => {
    showViewSettingDialog.value = true;
    newProject.value = currentProject.value
    getUserData(1, 10);
    getProjectUsers();
}

const delProject = () => {
    ElMessageBox.confirm('确认删除 【' + currentProject.value.projectName + '-' + currentProject.value.tagName + '】项目吗？', '提示', { type: 'warning', confirmButtonText: '确定删除', cancelButtonText: '取消' }).then(() => {
        del('/routing/project/' + currentProject.value.id).then(res => {
            ElMessage({ type: res.status ? 'success' : 'error', message: res.message });
            if (res.status) {
                getProjectList();
                getShareProject();
            }
        })
    }).catch(() => { })
}

const updateProject = () => {
    put('/routing/project', newProject.value).then(res => {
        ElMessage({ type: res.status ? 'success' : 'error', message: res.message })
        if (res.status) {
            getProjectList();
            getShareProject();
            showViewSettingDialog.value = false;
        }
    })
}

const clickRightEvent = (e, data) => {
    currentProject.value = data;
    let rightMenu = document.getElementById('rightMenu');
    rightMenu.style.left = e.clientX + "px";
    rightMenu.style.top = e.clientY + "px";
    showRightMenu.value = true;
}

const nextUserPage = (pageNum) => {
    getUserData(pageNum, 10)
}

onMounted(() => {
    getProjectList('', 1, 20);
    getShareProject();
});

</script>

<template>
    <div class="index" @click="showRightMenu = false">
        <div class="rightMenu" id="rightMenu" v-show="showRightMenu">
            <ul>
                <li @click="delProject"><el-icon style="margin-right: 5px;">
                        <Delete />
                    </el-icon>删除项目</li>
                <li @click="edit"><el-icon style="margin-right: 5px;">
                        <Edit />
                    </el-icon>重命名</li>
                <li @click="editViews"><el-icon style="margin-right: 5px;">
                        <View />
                    </el-icon>可见性</li>
            </ul>
        </div>
        <div class="area">
            <div class="area-title">
                <h4>我的项目（{{ projectList.length }}）</h4>
            </div>
            <el-divider />
            <div class="area-list" v-loading="loading">
                <div class="area-item item" @contextmenu.prevent="clickRightEvent($event, item)" @click="goWorkspace(item)"
                    v-if="projectList.length > 0" v-for="item in projectList" :key="item.id">
                    <div style="font-weight: bold;">{{ item.projectName }}</div>
                    <div style="margin-top: 10px;">{{ item.tagName }}</div>
                </div>
                <div class="area-item last" @click="showProjectDialog = true; newProject = {}">
                    <el-icon style="font-size: 28px; font-weight: bold;">
                        <Plus />
                    </el-icon>
                    <span style="padding-top: 5px;">创建项目</span>
                </div>
            </div>
            <div class="area-title">
                <h4>共享项目（{{ shareProject.length }}）</h4>
                <div class="area-list" v-loading="loading">
                    <div class="area-item item" @click="goWorkspace(item)" v-if="shareProject.length > 0"
                        v-for="item in shareProject" :key="item.id">
                        <div style="font-weight: bold;">{{ item.projectName }}</div>
                        <div style="margin-top: 10px;">{{ item.tagName }}</div>
                    </div>
                </div>
            </div>
            <el-divider />
            <el-dialog title="项目信息" v-model="showProjectDialog">
                <el-form label-position="top">
                    <el-form-item label="项目名称">
                        <el-input placeholder="输入项目名称" v-model="newProject.projectName"></el-input>
                    </el-form-item>
                    <el-form-item label="项目标签">
                        <el-input placeholder="输入项目标签" v-model="newProject.tagName"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <div style="width: 100%; text-align: right;">
                            <el-button type="info" style="width: 100px;" @click="showProjectDialog = false">取消</el-button>
                            <el-button type="primary" style="width: 100px;" @click="addProject">完成</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog title="可见性设置" v-model="showViewSettingDialog">
                <el-form label-position="top" @submit.native.prevent>
                    <el-form-item label="可见性">
                        <el-radio-group v-model="newProject.views">
                            <el-radio label="self">仅自己可见</el-radio>
                            <el-radio label="everyone">全部人可见</el-radio>
                            <el-radio label="point">部分人可见</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="用户" v-show="newProject.views == 'point'">
                        <div class="userList">
                            <el-tag closable @close="removeUser(item.userId)" style="margin-right: 10px;"
                                v-for="item in projectUserList" :key="item.id">{{ item.name }}</el-tag>
                        </div>
                        <el-input @keydown.enter.stop="getUserData(1, 10)" v-model="userKeyword" placeholder="关键字搜索"
                            clearable @clear="getUserData(1, 10)" :suffix-icon="Search"></el-input>
                        <el-table :data="userList" height="200">
                            <el-table-column label="姓名">
                                <template #default="scoped">
                                    <span>{{ scoped.row.userInfo.name }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="用户名">
                                <template #default="scoped">
                                    <span>{{ scoped.row.username }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center">
                                <template #default="scoped">
                                    <el-button
                                        @click="addUser(scoped.row.userInfo.id, scoped.row.userInfo.name, scoped.row.username)"
                                        text type="primary" size="small" :icon="Plus">添加</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination @current-change="nextUserPage" small layout="prev, pager, next" :total="total" />
                    </el-form-item>
                    <el-form-item>
                        <div style="width: 100%; text-align: center; margin-top: 20px;">
                            <el-button style="width: 100px;" @click="showViewSettingDialog = false;">取消</el-button>
                            <el-button @click="updateProject" style="width: 100px;" type="primary">确定</el-button>
                        </div>

                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>
<style scoped>
.index {
    padding: 10px;
    height: calc(100vh - 80px);
    overflow: auto;
}

.area-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.area-item {
    width: 150px;
    height: 150px;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 10px;
}

.last {
    border: 1px dashed var(--el-color-info);
}

.last:hover {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
}

.item {
    border: 2px solid var(--el-color-primary-light-7);
    background-color: var(--el-color-primary-light-9);
    box-shadow: 0px 3px 8px 0px var(--el-color-primary-light-7);
}

.item:hover {
    color: var(--el-color-primary-dark-2);
    box-shadow: 0px 6px 30px 0px var(--el-color-primary-light-7);
}

.area-title {
    padding-left: 10px;
}

.rightMenu {
    width: 200px;
    position: absolute;
    z-index: 1000;
    background-color: var(--el-color-primary-light-7);
    border-radius: 5px;
    padding: 10px;
    font-size: 14px;
    border: 1px solid var(--el-color-primary-light-5);
    box-shadow: 3px 4px 10px var(--el-color-primary-light-7);
}

.rightMenu>ul {
    margin: 0;
    padding: 0;
}

.rightMenu>ul>li {
    list-style: none;
    cursor: pointer;
    padding: 5px;
    display: flex;
    align-items: center;
    border-radius: 5px;
    border-bottom: 1px solid var(--el-color-primary-dark-2);
}

.rightMenu>ul>li:hover {
    background-color: var(--el-color-primary-dark-2);
    color: white;
}

.userList {
    margin-bottom: 10px;
    padding: 10px;
    width: 100%;
    border: 1px solid var(--el-color-primary-light-7);
}</style>